﻿using System.Drawing.Printing;
using System.Web;
using TuesPechkin;

namespace H2.NET.Web.Workflow.Tools
{
    /// <summary>
    /// 把指定网页导出到PDF文件
    /// </summary>
    public class ExportPdf : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            #region 参数准备
            var taskId = context.Request.QueryString["taskid"];
            if (string.IsNullOrEmpty(taskId))
            {
                EchoError(context, "TaskID不能为空！");
            }

            var filename = context.Request.QueryString["filename"];
            if (string.IsNullOrEmpty(filename))
            {
                EchoError(context, "导出文件名不能为空！");
            }
            #endregion

            var document = new HtmlToPdfDocument
            {
                GlobalSettings =
                {
                    ProduceOutline = true,
                    DocumentTitle = filename,
                    PaperSize = PaperKind.A4,
                    Margins =
                    {
                        All = 1.375,
                        Unit = Unit.Centimeters
                    }
                },
                Objects = {
                    new ObjectSettings
                    {
                        PageUrl = "http://" + context.Request.Url.Host + ":" + 
                                   context.Request.Url.Port + 
                                   "/pages/smd/views/taskview.aspx?showbtn=0&taskid=" + 
                                   taskId
                    }
                }
            };

            var converter = Factory.Create();
            var pdfBytes = converter.Convert(document);

            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            context.Response.AddHeader("Cache-Control", "no-cache");

            context.Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void EchoError(HttpContext context, string error)
        {
            Logging.GetLogger().Error(error);

            context.Response.ContentType = "text/plain";
            context.Response.Write(error);

            context.Response.End();
        }
    }
}